package com.geline.mybatisplus.handler;

import cn.hutool.core.util.StrUtil;
import com.geline.cloud.util.DynamicSqlUtil;
import com.geline.mybatisplus.annotation.ExtractStatus3;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.jdbc.core.JdbcTemplate;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @ExtractStatus3 处理器
 *
 * @author mx
 * @date 2025/10/10
 */
@Slf4j
public class ExtractStatus3Handler {
    private JdbcTemplate jdbcTemplate;

    public ExtractStatus3Handler(JdbcTemplate jdbcTemplate){
        this.jdbcTemplate = jdbcTemplate;
    }

    public void handle(Object entity, String sourceTable, String foreignKey) {
        BeanMap entityMap = BeanMap.create(entity);
        Map<String, Field> statusMap = new HashMap<>();
        Field[] fields = entity.getClass().getDeclaredFields();
        for(Field field : fields){
            ExtractStatus3[] statuses = field.getAnnotationsByType(ExtractStatus3.class);
            if(statuses != null && statuses.length>0){
                for(ExtractStatus3 status : statuses){
                    String totalKey = StrUtil.toCamelCase(status.totalKey());
                    Object value = entityMap.get(totalKey);
                    if(value!=null){
                        //只添加与子表相关的状态字段
                        statusMap.put(field.getName(),  field);
                    }else {
                        log.warn("@ExtractStatus3 缺少 totalKey 值: {}", totalKey);
                    }
                }
            }
        }
        log.debug("@ExtractStatus3 statusMap ={}", statusMap.keySet());

        Map<String, Object> updateValue = new HashMap<>();
        //再更新状态字段：比较总数与完成数
        for(String fieldName : statusMap.keySet()){
            Field statusField = statusMap.get(fieldName);
            ExtractStatus3 extractStatus = statusField.getAnnotation(ExtractStatus3.class);
            String column = extractStatus.statusColumn();
            if(StrUtil.isNotBlank(column)){
                column = StrUtil.toUnderlineCase(fieldName);
            }
            String selColumn = extractStatus.selectColumn();

            String totalKey = extractStatus.totalKey();
            //SELECT count(id) from t_sale_detail where sale_id=#{id}
            Object totalValue = entityMap.get(StrUtil.toCamelCase(totalKey));//1

            boolean findOther = false;
            String otherValues = extractStatus.otherValues();
            if(StrUtil.isNotBlank(otherValues)){
                String[] otherValueArray = otherValues.split(",");
                for(String otherValueStr : otherValueArray){
                    if(StrUtil.isNotBlank(otherValueStr)){
                        String otherStr = DynamicSqlUtil.quotaMark(statusField.getType(), otherValueStr);
                        String otherSql = String.format("select %s from %s where %s=#{id} and %s=%s", selColumn, sourceTable, foreignKey, column, otherStr);
                        otherSql = DynamicSqlUtil.parseSQL(otherSql, entityMap);
                        Double otherValue = this.jdbcTemplate.queryForObject(otherSql, Double.class);
                        otherValue = otherValue==null?0:otherValue;
                        log.info(">>>>@ExtractStatus3>>>> totalValue={}, otherValue={}", totalValue, otherValue);
                        if(otherValue>=Double.valueOf(totalValue.toString())){
                            findOther = true;
                            //更新主表状态为：其它值
                            entityMap.put(fieldName, otherValueStr);
                            updateValue.put(fieldName, otherValueStr);
                            break;
                        }
                    }
                }
            }
            if(!findOther){
                String overStr = DynamicSqlUtil.quotaMark(statusField.getType(), extractStatus.overValue());
                String partStr = DynamicSqlUtil.quotaMark(statusField.getType(), extractStatus.partValue());
                String overSql = String.format("select %s from %s where %s=#{id} and %s=%s", selColumn, sourceTable, foreignKey, column, overStr);
                overSql = DynamicSqlUtil.parseSQL(overSql, entityMap);
                //select count(1) from t_sale_detail where sale_id=#{id} and binding_status='2'
                String partSql = String.format("select %s from %s where %s=#{id} and %s=%s", selColumn, sourceTable, foreignKey, column, partStr);
                partSql = DynamicSqlUtil.parseSQL(partSql, entityMap);
                Double overValue = this.jdbcTemplate.queryForObject(overSql, Double.class);
                overValue = overValue==null?0:overValue;
                Double partValue = this.jdbcTemplate.queryForObject(partSql, Double.class);
                partValue = partValue==null?0:partValue;
                log.info(">>>>@ExtractStatus3>>>> totalValue={}, partValue={}, overValue={}", totalValue, partValue, overValue);
                if(overValue==0 && partValue==0){
                    //更新主表状态为：待处理
                    entityMap.put(fieldName, extractStatus.initValue());
                    updateValue.put(fieldName, extractStatus.initValue());
                }else if(overValue==0 && partValue>0){
                    //更新主表状态为：已完成
                    entityMap.put(fieldName, extractStatus.partValue());
                    updateValue.put(fieldName, extractStatus.partValue());
                }else if(overValue>=Double.valueOf(totalValue.toString())){
                    //更新主表状态为：已完成
                    entityMap.put(fieldName, extractStatus.overValue());
                    updateValue.put(fieldName, extractStatus.overValue());
                }else{
                    //更新主表状态为：部分完成
                    entityMap.put(fieldName, extractStatus.partValue());
                    updateValue.put(fieldName, extractStatus.partValue());
                }
            }
        }
        if(updateValue.size()>0){
            log.info(">>>> updateFieldValue[{}]={}", entity.getClass().getSimpleName(), updateValue);
        }
    }
}
